package com.github.binarywang.demo.wx.miniapp.wechat.service;

import cn.binarywang.wx.miniapp.api.WxMaQrcodeService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.json.JSONObject;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;

import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 小程序二维码生产
 *
 * @Description QRCodeImg
 * @Author guoyb
 * @Date 2024/5/11 9:36
 */
@Service
public class QRCodeImg {

    @Resource
    private WxMaQrcodeService wxMaQrcodeService;


    /**
     * 封装的api接口实现
     */
    @SneakyThrows
    public void createQR(){
        String scene="a=1",  page="pages/index/index";
        wxMaQrcodeService.createWxaCodeUnlimit(scene,page);

        // 发送请求参数
        JSONObject paramJson = new JSONObject();
        paramJson.put("scene", scene);
        paramJson.put("page", "pages/index/index"); // 这里特别注意前面不要加 '/'
        paramJson.put("width", 430);
        paramJson.put("auto_color", true); // 自动配置线条颜色
        paramJson.put("is_hyaline", true); // 背景色透明

    }

    public byte[] generateMiniProgramQRCode(String accessToken, String scene, String pageEncoded) throws IOException {
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;

        //        String url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + accessToken;
        // 正式版为 "release"，体验版为 "trial"，开发版为 "develop"。默认是正式版。
        String env_version = "trial";

        // 构建请求参数
        //        String postData = "{\"scene\":\"" + scene + "\", \"path\":\"" + pageEncoded + "\", \"width\":430,\"env_version\":\"trial\"}";
        String postData = "{\"scene\":\"" + scene + "\", \"page\":\"" + pageEncoded + "\", \"width\":430,\"env_version\":\"" + env_version + "\"}";
        //        String postData = "{\"scene\":\"" + scene + "\", \"width\":430,\"env_version\":\"trial\"}";


        // 发送POST请求
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.getOutputStream().write(postData.getBytes("UTF-8"));

        // 读取响应数据
        InputStream inputStream = connection.getInputStream();
        byte[] buffer = StreamUtils.copyToByteArray(inputStream);

        // 解析响应数据，获取小程序码的URL

        return buffer;
    }




}
